import {
  ChatContext,
  IndexContext,
  useChatContextProvider,
} from "@/pages/BigScreen/context/store";
import Chat from "./Chat";
import Head from "./Head";

import styles from "./index.module.less";
import useIndex from "./useIndex";
import { useGlobalData } from "@/pages/BigScreen/context/chat";
import AppTooltip from "../AppTooltip";
import { TableProvider } from "@/pages/BigScreen/context/table";
import {
  forwardRef,
  useContext,
  useEffect,
  useImperativeHandle,
  useState,
} from "react";
import History from "./History";
import { ChatTabContext } from "@/pages/BigScreen/context/chatTab";
import { default_scene, new_session } from "@/utils/common";
import { BigScreenContext } from "@/pages/BigScreen/context/BigScreenContext";
import { default_ask } from "@/utils/text";

const Conversation = forwardRef((props: any, ref) => {
  const { setCurrentKey, initNavList } = useContext(BigScreenContext);

  const [tabIndex, setTabIndex] = useState("0");

  const indexInst = useIndex({ tabIndex });
  const chatContextInst = useChatContextProvider({ ...indexInst } as any);
  const { clearChatEffect, isLoading, onHandleChangeTalk, handle } =
    chatContextInst;
  const { clearChatMemo, chatInputFooterRef } = useGlobalData();

  const toHandleNewChat = () => {
    // 对话中不允许新建对话
    if (isLoading) return;

    let sessionId = new_session;
    let memoInfo = {
      ...default_scene,
    };
    // 设置 会话插件缓存
    // handleChangeChatMemo(sessionId, memoInfo);
    clearChatEffect();
    clearChatMemo();
    chatInputFooterRef?.current?.handleChatOlIndex("");
    // 切换 tab
    setTabIndex("0");

    // 切换场景
    setCurrentKey("question");
    initNavList();
    onHandleChangeTalk("add", {} as any, () => {
      setTimeout(() => {
        handle(default_ask, {
          newChat: true,
          list: [],
        });
      }, 200);
    });
  };

  useImperativeHandle(ref, () => ({
    // 暴露给外部 快速提问
    handleChat: (str = "") => {
      // 1. 切换为对话模式
      setTabIndex("0");
      setTimeout(() => {
        handle(str);
      });
    },

    handleNewChat: () => {
      toHandleNewChat();
    },
  }));

  useEffect(() => {
    setTimeout(() => {
      handle(default_ask);
    }, 300);
  }, []);

  return (
    <ChatTabContext.Provider value={{ tabIndex, changeTab: setTabIndex }}>
      <IndexContext.Provider value={{ ...indexInst } as any}>
        <ChatContext.Provider value={{ ...chatContextInst }}>
          <TableProvider>
            <div className={styles.conversation}>
              <Head tab={tabIndex} onChange={setTabIndex} />

              {tabIndex === "0" && (
                <>
                  <Chat scrollDomRef={indexInst.scrollDomRef} />

                  {/* 回到底部 */}
                  {indexInst.showBack && (
                    <AppTooltip overlay="回到底部" placement="right">
                      <div
                        className={styles["chat-back-bottom"]}
                        onClick={indexInst.scrollToBottom}
                      >
                        <i className="iconfont icon-down-end"></i>
                      </div>
                    </AppTooltip>
                  )}
                </>
              )}

              {tabIndex === "1" && (
                <History
                  visible={tabIndex === "1"}
                  handlePopupVisible={() => setTabIndex("0")}
                ></History>
              )}
            </div>
          </TableProvider>
        </ChatContext.Provider>
      </IndexContext.Provider>
    </ChatTabContext.Provider>
  );
});
export default Conversation;
